package com.guaoran.source.mybatis.demo.plugins;

import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;

import java.util.Properties;

/**
 * @author : 孤傲然
 * @Description :
 *  自定义插件
 * @date :2018/5/24 21:41
 */
@Intercepts({
        @Signature(
                // 只能是: StatementHandler | ParameterHandler | ResultSetHandler | Executor 类或者子类
                type = Executor.class,
                //表示：拦截Executor的query方法
                method = "query",
                //args参数描述：query 有很多的重载方法，需要通过方法签名来指定具体拦截的是那个方法
                //指该query方法，有几个参数，这几个参数都是什么类型， 必须保持一致。
                // org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(java.lang.String, java.lang.Object, org.apache.ibatis.session.RowBounds).numberLine:148
                args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}
        )
})
public class DemoPlugin implements Interceptor {
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
        BoundSql boundSql = mappedStatement.getBoundSql(invocation.getArgs()[1]);
        System.out.println(String.format("DemoPlugin output sql = %s , param=%s", boundSql.getSql(),boundSql.getParameterObject()));
        return invocation.proceed();
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }
    @Override
    public void setProperties(Properties properties) {

    }
}


